matroskin 0.1.0

whatsminer api client lib
Documentation
# TCP Data Framing

This section describes the data framing required for sending and receiving JSON payloads over TCP. All communication is a sequence of length-prefixed messages.

## Sending a Request

1. Generate the JSON request and encode it as an ASCII string.
2. Calculate the byte length of the JSON string.
3. Connect to the device on port **4433**.
4. Send the length as a 4-byte little-endian integer.
5. Send the full JSON string.

## Receiving a Response

1. Read the first 4 bytes from the socket to determine the length of the incoming JSON response.
2. Read the specified number of bytes to receive the complete JSON response string.

The connection will be automatically closed after 300 seconds of inactivity.

## Examples

### Sending a Request (C Example)

```c
int tcpWrite(int soc_id, const cJSON *jsonData)
{
    int str_len = 0;
    int ret = -1;
    uint8_t arr_len[6];
    char *p_str = cJSON_PrintUnformatted(jsonData);

    if (!p_str) {
        return -1;
    }

    str_len = strlen(p_str);
    memcpy(arr_len, &str_len, 4);

    send(soc_id, arr_len, 4);
    ret = send(soc_id, p_str, strlen(p_str));
    if (ret != strlen(p_str)) {
        ret = -1;
    }

    free(p_str);
    return ret;
}
```

### Receiving a Response (C Example)

```c
int rsp_len = 0, read_len = 0;
unsigned char arr_rsp[8192];
// read the first 4 byte for json response length.
recv(socket, (unsigned char *)&rsp_len, 4);
if (rsp_len > sizeof(arr_rsp)) {
    rsp_len = sizeof(arr_rsp);
}

memset(arr_rsp, 0, sizeof(arr_rsp));
read_len = recv(socket, arr_rsp, rsp_len);

if (read_len == rsp_len) {
    return cJSON_Parse((const char *)arr_rsp); // remember to call cJSON_Delete free this malloc buffer.
} else if (read_len == 0) {
    printf("read len = 0, maybe disconnect.\n");
    return NULL;
}
```